#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import shutil
import subprocess
import time

def convert_to_codec(input_file, codec='flac'):
    """
    将音频文件转换为 指定 格式
    
    :param input_file: 输入音频文件路径
    """
    if input_file.endswith(f'.{codec}'):
        print(f'{input_file} is already in {codec} format, skipping conversion')
        return
    # 构造输出文件名，替换后缀为指定格式
    output_file = os.path.splitext(input_file)[0] + f'.{codec}'
    if os.path.exists(output_file):
        print(f'{output_file} already exists, skipping conversion')
        os.remove(input_file)
        return
    
    # 使用 ffmpeg 进行转换
    command = ["ffmpeg", "-i", input_file, output_file]
    try:
        subprocess.run(command, check=True)
        print(f'Successfully converted {input_file} to {output_file}')
        os.remove(input_file)
    except subprocess.CalledProcessError as e:
        print(f'Error during conversion: {e}')

if __name__ == '__main__':
    # 支持转换的音频文件扩展名
    audio_extensions = ('.ape', '.wav', '.dts', '.flac', '.mp3', '.dff')

    # 指定要转换的文件所在目录
    directory_path = r'H:\demo'  # 修改为你的目录
    
    # 遍历目录中的音频文件，并转换为 FLAC
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            if file.endswith(audio_extensions):
                file_path = os.path.join(root, file)
                convert_to_codec(file_path, 'flac')
